package com.gzhryc.shared_device.oem.micro.api.controllers.xcx.v1.member;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.util.Base64;

import com.gzhryc.common.DateTools;
import com.gzhryc.common.IDTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.base.models.VerifyCodeData;
import com.gzhryc.shared_device.common.payment.dao.enums.WXPayConfigEnum;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.ResourceAPIServer;
import com.gzhryc.shared_device.oem.code.business.dao.db.CouponActivity;
import com.gzhryc.shared_device.oem.code.business.dao.enums.CouponActivityEnum;
import com.gzhryc.shared_device.oem.code.business.services.CouponActivityService;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.member.LoginMemberSessionManager;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;
import com.gzhryc.shared_device.oem.code.member.services.MemberService;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.dao.db.UserTransferMoneyWX;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.code.user.services.UserTransferMoneyWXService;
import com.gzhryc.shared_device.oem.micro.api.MicroConstants;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.UploadImgRequest;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.UploadImgResponse;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.member.AgentBindRequest;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.member.MemberInfoUpdateRequest;
import com.gzhryc.weixin.xcx.XcxAuthorityApi;
import com.gzhryc.weixin.xcx.dto.Jscode2SessionResponse;

public class MemberController {

    static Logger log = Logger.getLogger(MemberController.class);

    @Route(value = { "/xcx/v1/member/info/update.do" }, method = "POST")
    public DefaultAPIResponse doUpdateInfo(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "修改失败");
        MemberInfoUpdateRequest apiReq = WebUtils.getJsonRequest(request, MemberInfoUpdateRequest.class);
        if (apiReq != null && (StringTools.isNotBlank(apiReq.getBody().getNickname()) || StringTools.isNotBlank(apiReq.getBody().getFaceImg()))) {
            LoginMember loginMember = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
            if (MicroConstants.MemberDefaultName.equals(apiReq.getBody().getNickname())) {
                apiResp.setMsg("请修改您的昵称");
                return apiResp;
            }
            boolean newPeople = MicroConstants.MemberDefaultName.equals(loginMember.getNickname());

            Member member = new Member();
            member.setId(loginMember.getId());
            if(StringTools.isNotBlank(apiReq.getBody().getNickname())) {
                member.setNickname(apiReq.getBody().getNickname());
            }
            if(StringTools.isNotBlank(apiReq.getBody().getFaceImg())) {
                member.setFaceImg(apiReq.getBody().getFaceImg());
            }
            try {
                if (MemberService.self().updateNotNull(member)) {
                    loginMember.setNickname(member.getNickname());
                    if (newPeople) {
                        List<CouponActivity> couponActivityList = CouponActivityService.self().findEnableByType(CouponActivityEnum.Type.NewPeople.index());
                        if (couponActivityList != null && couponActivityList.size() > 0) {
                            OperateInfo operateInfo = new OperateInfo();
                            operateInfo.setProgramType(MicroConstants.PROGRAM_TYPE);
                            operateInfo.setProgramTypeName(MicroConstants.PROGRAM_TYPE_NAME);
                            operateInfo.setOperatorType(EOperatorType.Member.index());
                            operateInfo.setOperatorTypeName(EOperatorType.Member.note());
                            operateInfo.setOperator(loginMember.getFullName());
                            for (CouponActivity couponActivity : couponActivityList) {
                                if (!CouponActivityService.self().memberNewReceive(couponActivity, loginMember.getId(), loginMember.getNickname(), operateInfo)) {
                                    log.error("{{0}}会员领取新人优惠券失败", loginMember.getId());
                                }
                            }
                        }
                    }
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                apiResp.setMsg(e.getMessage());
            }
        }
        return apiResp;
    }

    @Route(value = "/xcx/v1/member/img/upload.do", method = "post")
    public UploadImgResponse uploadImg(HttpServletRequest request, HttpServletResponse response) {
        UploadImgResponse apiResp = new UploadImgResponse(ClientAPICodeConstants.EXECUTE_ERROR, "上传失败");
        UploadImgRequest apiReq = WebUtils.getJsonRequest(request, UploadImgRequest.class);
        log.info("会员图片上传：{{0:json}}", apiReq);
        if (apiReq != null) {
            String content = apiReq.getBody().getContent();
            if (StringTools.isBlank(content)) {
                apiResp.setMsg("无上传内容，请检查");
                return apiResp;
            }
            String imgData = content.replace("data:image/jpeg;base64,", "");
            FileOutputStream fos = null;
            try {
                // 解码base64
                Base64 decoder = new Base64();
                byte[] data = decoder.decode(imgData);
                for (int i = 0; i < data.length; i++) {
                    if (data[i] < 0) {
                        data[i] += 256;
                    }
                }
                String tempPath = PropertyTools.get().getString("tempPath");
                File file = new File(tempPath + "/" + IDTools.getUUID() + ".jpg");
                fos = new FileOutputStream(file);
                fos.write(data);
                fos.flush();
                fos.close();
                String path = ResourceAPIServer.self().uploadImg(ResourceAPIServer.memberPath, file);
                if (StringTools.isNotBlank(path)) {
                    apiResp.setCode(DtoConstants.SUCCESS, null);
                    apiResp.getBody().setImgPath(path);
                    String resDomain = PropertyTools.get().getString(MicroConstants.ResourceDomain);
                    apiResp.getBody().setResDomain(resDomain);
                }
            } catch (IOException e) {
                log.error("图片上传错误", e);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/xcx/v1/member/agent/bind.do" }, method = "POST")
    public DefaultAPIResponse doAgentBind(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "绑定提现失败");
        AgentBindRequest apiReq = WebUtils.getJsonRequest(request, AgentBindRequest.class);
        if (StringTools.isNotBlank(apiReq.getBody().getAppId()) && StringTools.isNotBlank(apiReq.getBody().getWxCode())
            && StringTools.isNotBlank(apiReq.getBody().getPhone())) {

            String key = apiReq.getBody().getPhone() + "_" + apiReq.getBody().getPt();
            VerifyCodeData verifyCodeData = LoginMemberSessionManager.self().getVerifyCode(key);
            if (verifyCodeData == null) {
                apiResp.setMsg("请填写正确的手机验证码");
                return apiResp;
            }

            if (DateTools.differenceMinute(verifyCodeData.getCreateDate(), new Date()) > 10) {
                LoginMemberSessionManager.self().removeVerifyCode(key);
                apiResp.setMsg("手机验证码超时");
                return apiResp;
            }

            if (apiReq.getBody().getPhoneValid().equals(verifyCodeData.getCode())) {
                PayServiceFactory.AppConfig config = PayServiceFactory.self().getWxConfig(apiReq.getBody().getAppId());
                if (config != null) {
                    try {
                        XcxAuthorityApi xcxApi = new XcxAuthorityApi(config.getAppId(), config.getAppSecret());
                        Jscode2SessionResponse data = xcxApi.jscode2Session(apiReq.getBody().getWxCode());
                        if (data != null && StringTools.isNotBlank(data.getOpenid())) {
                            User user = UserService.self().getByPhone(apiReq.getBody().getPhone());
                            if (user != null) {
                                UserTransferMoneyWX wxUser = UserTransferMoneyWXService.self().getByKeys(apiReq.getBody().getAppId(), data.getOpenid(), user.getId());
                                if (wxUser != null) {
                                    apiResp.setMsg("该微信已绑定代理");
                                }

                                UserTransferMoneyWX transferMoneyWX = new UserTransferMoneyWX();
                                transferMoneyWX.setAppId(apiReq.getBody().getAppId());
                                transferMoneyWX.setOpenId(data.getOpenid());
                                transferMoneyWX.setUserId(user.getId());
                                transferMoneyWX.setAppType(WXPayConfigEnum.AppType.wxxcx.index());
                                transferMoneyWX.setNickname(apiReq.getBody().getNickname());
                                transferMoneyWX.setFaceImg(apiReq.getBody().getFaceImg());
                                transferMoneyWX.setSex(user.getSex());
                                transferMoneyWX.setName(apiReq.getBody().getName());
                                transferMoneyWX.setPhone(user.getPhone());

                                if (UserTransferMoneyWXService.self().add(transferMoneyWX)) {
                                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                                    LoginMemberSessionManager.self().removeVerifyCode(key);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }else {
                apiResp.setMsg("手机验证码不正确");
                return apiResp;
            }
        }
        return apiResp;
    }

}
